package com.imooc.netty.samples.$03;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 测试方法
 * 1)运行该程序
 * 2)开打cmd控制台,输入"telnet localhost 8001"或者"telnet 127.0.0.1 8001"
 *   此时该程序会打印“one client conn: Socket[addr=/0:0:0:0:0:0:0:1,port=61915,localport=8001]”类似的日志
 * 3)在telnet中随便输入字符串然后按回车
 *
 * 补充:telnet退出方法,先按"ctrl+]"、然后输入"quit"即可
 */
public class BIOEchoServer {
    public static void main(String[] args) throws IOException {
        // 启动服务端，绑定8001端口
        ServerSocket serverSocket = new ServerSocket(8001);
        System.out.println("server start");

        while (true) {
            // 开始接受客户端连接
            Socket socket = serverSocket.accept();
            System.out.println("one client conn: " + socket);

            // 启动线程处理连接数据(老方法)
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try {
                        // 读取数据
                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String msg;
                        while ((msg = reader.readLine()) != null) {
                            System.out.println("receive msg: " + msg);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            // 启动线程处理连接数据(lambda表达式)
//            new Thread(() -> {
//                try {
//                    // 读取数据
//                    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//                    String msg;
//                    while ((msg = reader.readLine()) != null) {
//                        System.out.println("receive msg: " + msg);
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }).start();
        }
    }
}
